<?php
	defined('RUN') or die('No access');
	
	class Product_categoryModel
	{
		private $tables='product_category';
	    public function getCategory($fields='*',$parent_id = 0)
		{
			return Model::getDataSql("SELECT ".$fields." FROM ".$this->tables." WHERE status =1 ORDER BY `name` ASC, `sort` ASC, `id` DESC");
		}
        public function countRows()
		{
			$sql = "SELECT COUNT(`id`) as `total` FROM ".$this->tables;
			$query = Db::query($sql);
			$result = Query::fetch($query);
			$total = $result['total'];
			
			return $total;
		}
		public function getByPage($fields='*', $page, $per_page = 20)
		{
			$order = '`updated` DESC, `id` DESC';
			$conditions='';
			$offset = ($page - 1) * $per_page;
			$data = Model::getData($this->tables, $fields, $conditions, $per_page, $offset, $order);
			return $data;
		}
		public function getById($id,$fields='*')
		{
			$condition = array(
					'field' => 'id',
					'value' => $id
				);

			$cat = Model::getData($this->tables, $fields, $condition);
			if ($cat)
				return $cat[0];

			return FALSE;
		}
		public function getCategoriesAll($fields='*',$parent_id = 0) {
			$category_data = array();
		
			$rows =  Model::getDataSql("SELECT ".$fields." FROM ".$this->tables." WHERE `parent_id` = '" . (int)$parent_id . "' ORDER BY `sort`, `name` ASC");
			foreach ($rows  as $result) {
				$category_data[] = array(
					'id'     => $result['id'],
					'name'   => $this->getPath($result['id']),
                    'parent_id' => $result['parent_id'],
					'status' => $result['status'],
					'sort'   => $result['sort']
				);
			
				$category_data = array_merge($category_data, $this->getCategoriesAll($fields,$result['id']));
			}	
	
    		return $category_data;
    	}
    	
    	public function getPath($category_id) {
    		$rows =  Model::getDataSql("SELECT `name`, `parent_id` FROM ".$this->tables." WHERE id = '" . (int)$category_id . "'  ORDER BY `sort`, `name` ASC");
    		
    		if ($rows[0]['parent_id']) {
    			return $this->getPath($rows[0]['parent_id']) . ' > ' . $rows[0]['name'];
    		} else {
    			return $rows[0]['name'];
    		}
    	}
		public function add($data)
		{
			return Model::insertData($this->tables, $data);
		}

		public function update($data, $id)
		{
			$condition = array(
					'field' => 'id',
					'value' => $id
				);
			
			return Model::updateData($this->tables, $data, $condition);
		}

		public function delete($id)
		{
			$condition = array(
					'field' => 'id',
					'value' => $id
				);

			return Model::deleteData($this->tables, $condition);
		}
	}
